package com.itheima.controller;

import com.itheima.pojo.Ecometeorology;
import com.itheima.pojo.Flux;
import com.itheima.pojo.Meteorology;
import com.itheima.pojo.Result;
import com.itheima.service.EcometeorologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

import static org.mockito.internal.matchers.text.ValuePrinter.print;

// 气象接口
@RestController
@RequestMapping("/ecometeorology")
public class EcometeorologyController {
    @Autowired
    private EcometeorologyService ecometeorologyService;

    // 上传气象数据接口
    @PostMapping("/uploadData")
    public Result uploadData(@RequestParam("excelFile") MultipartFile file) {
        System.out.println(11);
        // 检查上传的文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.error("上传的文件不存在或为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 使用ExcelUtil类读取Excel文件内容并转换为List<Meteorology>
            List<Ecometeorology> ecometeorologyList = com.itheima.utils.EcometeorologyExcelUtil.readExcel(inputStream);

            // 遍历List<Meteorology>，将数据存储到数据库中
            for (Ecometeorology ecometeorology : ecometeorologyList) {
                // 检查数据库中是否有与当前meteorology的timestamp相同的数据

                Ecometeorology existingEcometeorology = ecometeorologyService.findEcometeorologyByTimestamp(ecometeorology.getTimestamp());

                if (existingEcometeorology == null) {
                    System.out.println("该条数据不存在并插入:"+ecometeorology);

                    // 如果不存在则插入数据
                    ecometeorologyService.add(ecometeorology);
                }
            }

            return Result.success("文件上传成功，数据已存储");

        } catch (IOException e) {
            return Result.error("文件读取的时候失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error("数据处理的时候失败: " + e.getMessage());
        }
    }

    // 查询某个时间段数据接口
    @GetMapping("/findEcometeorologyByTimeRange")
    public Result<List<Ecometeorology>> findEcometeorologyByTimeRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        // 无处理数据库中无部分或这全部数据的逻辑
        List<Ecometeorology> list = ecometeorologyService.findEcometeorologyByTimeRange(startTime, endTime);
        System.out.println(list);
        return Result.success(list);

        // *处理数据库中无部分或这全部数据的逻辑
    }

    // 查询数据库中现有数据的最新日期的当天的全部数据
    @GetMapping("/findEcometeorologyInLatestDayData")
    public Result<List<Ecometeorology>> findEcometeorologyInLatestDayData(){
        List<Ecometeorology> list = ecometeorologyService.findEcometeorologyInLatestDayData();
        System.out.println(list);
        return Result.success(list);
    }

    // 查询数据通过前端用户选择的单个时间
    @GetMapping("/findEcometeorologyByUserSelectSingleTimeStamp")
    public Result<Ecometeorology> findEcometeorologyByUserSelectSingleTimeStamp(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime singleTime) {
        // 尝试查询指定时间点的数据
        Ecometeorology ecometeorology = ecometeorologyService.findEcometeorologyByUserSelectSingleTimeStamp(singleTime);

        // *处理数据库中无部分或这全部数据的逻辑

        // 如果指定时间点的数据不存在
        if (ecometeorology == null) {
            // 获取上个月的同一天
            LocalDateTime lastMonthSameDate = singleTime.minusMonths(1);

            // 检查上个月的同一天是否存在（例如2月没有30日）
            if (lastMonthSameDate.getDayOfMonth() != singleTime.getDayOfMonth()) {
                // 如果不存在，尝试获取上个月的最后一天
                LocalDate lastMonthLastDay = lastMonthSameDate.toLocalDate().with(TemporalAdjusters.lastDayOfMonth());
                lastMonthSameDate = LocalDateTime.of(lastMonthLastDay, singleTime.toLocalTime());
            }

            // 查询上个月的数据
            ecometeorology = ecometeorologyService.findEcometeorologyByUserSelectSingleTimeStamp(lastMonthSameDate);

            // 如果上个月的数据也不存在，可以选择返回默认值或提示信息
            // 如果上个月的数据也不存在，返回默认值
            if (ecometeorology == null) {
                ecometeorology = new Ecometeorology();
                ecometeorology.setTimestamp(singleTime); // 设置时间戳为请求的时间
                ecometeorology.setBPAvg(0.0); // 默认值
                ecometeorology.setEAvg(0.0);
                ecometeorology.setRHAvg(0.0);
                ecometeorology.setPMRH(0.0);
                ecometeorology.setTSP(0.0);
                ecometeorology.setCO2Avg(0.0);
                ecometeorology.setWSWVc3(0.0);
                ecometeorology.setWSWVc2(0.0);
                ecometeorology.setWSWVc1(0.0);
                ecometeorology.setPMStatus(0.0);
                ecometeorology.setRecord(0.0);
                ecometeorology.setBattVoltMin(0.0);
                ecometeorology.setPM10(0.0);
                ecometeorology.setPM2Point5(0.0);
                ecometeorology.setPMTemp(0.0);
                ecometeorology.setPTemp(0.0);
                ecometeorology.setTempAvg(0.0);

            }
        }

        // *处理数据库更新不及时的逻辑

        return Result.success(ecometeorology);
    }

    // 默认查询数据接口,返回数据库中的时间节点最新的数据
    @GetMapping("/findLatestEcometeorology")
    public Result<Ecometeorology> findLatestEcometeorology() {
        Ecometeorology latestEcometeorology = ecometeorologyService.findLatestEcometeorology();
        if (latestEcometeorology == null) {
            return Result.error("No ecometeorology data found");
        }
        return Result.success(latestEcometeorology);
    }

}
